package com.vehicle.core.rest;

import com.vehicle.core.dto.Result;
import com.vehicle.core.exception.ExceptionConstants;
import com.vehicle.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author shouhan
 * @version 1.0
 * @date 2018/12/28
 * @desc 全局异常处理抽象类
 * @see
 * @since 1.0
 */
public abstract class BaseGlobalExceptionsAdviceHandler {

    private Logger LOGGER = LoggerFactory.getLogger(BaseGlobalExceptionsAdviceHandler.class);

    /**
     * 处理自定义业务异常
     * //todo 自定义异常一定要放在系统异常前面 否则自定义异常将不起作用
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public Result handleServiceException(ServiceException e) {
        Result result = new Result(e.getCode(), null);
        result.setServerTime(new Date());
        String message = e.getMessage();
        if (org.springframework.util.StringUtils.isEmpty(message)) {
            //todo 此处根据code码 读取message项目启动初始化到redis中
            message = "出错啦， 快找开发小哥哥！";
            result.setMessage(message);
        }
        return result;
    }

    /**
     * 处理系统异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result handleSystemException(HttpServletRequest request, Exception e) {
        LOGGER.error(e.getMessage());  // 记录错误信息

        Result result = null;
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            // 处理404错误
            result = new Result(ExceptionConstants.SERVER_NOT_FOUND, null);
            result.setStack(e.getMessage());
        } else {
            result = new Result(ExceptionConstants.WEB_SERVER_PROGRAM_ERROR, null);
            result.setStack(e.getMessage());
        }
        // 存入DB中
        try {
            result.setServerTime(new Date());
            addServerExceptionLog(request, e);
            LOGGER.error("异常接入日志");
        } catch (Exception ex) {
            LOGGER.error("add server exception error:  {}", e.getMessage());
        }
        return result;
    }

    protected abstract void addServerExceptionLog(HttpServletRequest request, Exception e);


}
